import { reactive } from "vue";
import axios from "axios";
import useMenu from './menu';
import router, { routerImports } from "../router";

let isAdmin = 0;
const menu = useMenu();

let getCurrentUser = () => {
	axios({
	  method: "GET",
	  url: `/api/employee/getCurrentUser`,
	}).then((resp) => {
	  if (resp.data.code === 200) {
		user.num = resp.data.data.num;
		user.name = resp.data.data.name;
	  } else {
		ElMessage.error(resp.data.msg);
		console.log("出现逻辑异常:", resp);
	  }
	}).catch((e) => {
	  console.log("出现异常:", e);
	})
  };

const user = reactive({
	isLogin: false,
	num: null,
	name: null,
	login: (type) => {
		isAdmin = type;
		user.isLogin = true;
		createMenu();
		getCurrentUser();
	},
	logout: () => {
		localStorage.removeItem("token");
		user.name = '';
		user.num = '';
		user.isLogin = false;
		router.push('/');
	},
});

export default function useUser() {
	return user;
}

const createMenu = () => {
	if (isAdmin === 0) {
		axios.get("/menu.json").then((resp) => {
			createRoute(null, resp.data);
			menu.setMenu(resp.data);
		})
	} else {
		axios.get("/menu2.json").then((resp) => {
			createRoute(null, resp.data);
			menu.setMenu(resp.data);
		})
	}
}

const createRoute = (parent, arr) => {
	arr.forEach((item) => {
		item.component = routerImports[item.name];
		if (parent) {
			router.addRoute(parent, item);
		} else {
			router.addRoute(item);
		}

		if (item.children) {
			createRoute(item.name, item.children);
		}
	});
}